<template>
  <div>
    <el-form ref="contractAddForm" :model="contractAdd" label-position="top">
      <!-- style="width: 100%;" -->
      <el-row>
        <el-col :span="10">
          <el-form-item label="合同名称：" prop="contractName">
            <el-input v-model="contractAdd.contractName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="工程名称：" prop="projectName">
            <el-input v-model="contractAdd.projectName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="工程地点：" prop="workRegion">
            <el-input v-model="contractAdd.workRegion" autocomplete="off" />
          </el-form-item>
          <el-form-item label="签订甲方：" prop="otherCustomer">
            <el-input v-model="contractAdd.otherCustomer" autocomplete="off" />
          </el-form-item>
          <el-form-item label="签订乙方：" prop="company">
            <el-input v-model="contractAdd.company" autocomplete="off" />
          </el-form-item>
          <el-form-item label="签订地址：" prop="signingAddress">
            <el-input v-model="contractAdd.signingAddress" autocomplete="off" />
          </el-form-item>
          <el-form-item label="签订日期：" prop="signingDate">
            <el-date-picker v-model="contractAdd.signingDate" type="date" placeholder="选择日期" :size="size"
              format="YYYY/MM/DD" value-format="YYYY/MM/DD" />
          </el-form-item>
          <el-form-item label="合同工期">
            <el-date-picker v-model="contractAdd.date" type="daterange" unlink-panels range-separator="To"
              start-placeholder="开始日期" end-placeholder="结束日期" size="large" />
          </el-form-item>
        </el-col>
        <el-col :span="12" style="margin-left: 30px">
          <el-from-item label="施工类型:" prop="constructionTypeList">
            <span>施工类型</span>
            <el-select v-model="constructionTypeList" multiple placeholder="选择施工类型" style="width: 240px"
              @change="changeType">
              <el-option v-for="item in typeList" :key="item.id" :label="item.constructionType" :value="item.id" />
            </el-select>
          </el-from-item>

          <div v-for="(item, index) in selectedType">
            <el-col :span="10">
              <el-form-item :label="item.constructionType + ' 单位'">
                <el-input autocomplete="off" :placeholder="item.unitName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-left: 10px">
              <el-form-item :label="item.constructionType + ' 单价(元)'">
                <el-input v-model="item.unitPrice" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item :label="item.constructionType + ' 数量'">
                <el-input v-model="item.number" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-left: 10px">
              <el-form-item :label="item.constructionType + ' 金额'">
                <el-input autocomplete="off" :placeholder="item.number * item.unitPrice" disabled />
              </el-form-item>
            </el-col>
          </div>

        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="addContract">{{ submitContent }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { get, post, tip, WAREHOUSE_CONTEXT_PATH } from "@/common";
import { Plus } from "@element-plus/icons-vue";

const contractAdd = ref({
  contractName: "", projectName: ""
  , workRegion: "", otherCustomer: ""
  , company: "", signingAddress: "", signingDate: ""
  , productNum: "", ifPurchase: "3", selectedType: []
  ,date:[]

});

const submitContent = ref("确认")

// 获得所有类型
const typeList = ref();
const getTypeList = () => {
  get("/constructionType/constructionType-list").then(result => {
    typeList.value = result.data;
  })
}

getTypeList();

const constructionTypeList = ref([]);

// 读取到的表格数据
const tableList = ref([])
const tableHeader = ref({})

const active = ref(1)




const content2DocTable = (contentList) => {
  let tableContent = { id: '', productName: '', unit: '', quantity: '', price: '', total: '' }
  const keys = Object.keys(tableContent);

  for (let i = 0; i < contentList.length / 6; i++) {
    for (let index = 0; index < 6; index++) {
      tableContent[keys[index]] = contentList[i * 6 + index]
    }
    tableList.value.push(Object.assign({}, tableContent))
  }
  tableHeader.value = tableContent
}

const content2DocList = (content) => {
  let list = []
  let list2 = []
  for (let i in content) {
    content[i] = content[i].replace(/\r/g, '')
    content[i] = content[i].replace(/" "/g, "")
    if (content[i] != "") {
      list.push(content[i])
    }
  }
  list2.push(list[0])
  for (let i = 0; i < list.length; i++) {
    let colonIndex = list[i].indexOf("：");

    if (colonIndex !== -1) { // 如果找到冒号
      // 获取冒号后面的字符串，并去除空格
      let extractedText = list[i].substring(colonIndex + 1).trim();
      list2.push(extractedText)
    }
  }
  let j = 0

  for (let i in contractAdd.value) {
    contractAdd.value[i] = list2[j]
    j++;
  }
}

// 接收的合同数据
const content2List = (json) => {
  // let json = JSON.parse(textList)
  let content = [];
  content.push(json[0])
  for (let i = 0; i < json.length; i++) {
    let colonIndex = json[i].indexOf("：");

    if (colonIndex !== -1) { // 如果找到冒号
      // 获取冒号后面的字符串，并去除空格
      let extractedText = json[i].substring(colonIndex + 1).trim();
      content.push(extractedText)
    }
  }
  let j = 0

  for (let i in contractAdd.value) {
    contractAdd.value[i] = content[j]
    j++;
  }
}

// 接收的表格数据
const content2Table = (text) => {
  let json = JSON.parse(text);
  let contentList = []
  for (let i = 0; i < json.length; i++) {
    for (let j = 0; j < json[i].data.length; j++) {
      for (let z = 0; z < json[i].data[j].length; z++) {
        contentList.push(json[i].data[j][z].text)
      }
    }
  }
  let tableContent = { id: '', productName: '', unit: '', quantity: '', price: '', total: '' }
  const keys = Object.keys(tableContent);

  for (let i = 0; i < contentList.length / 6; i++) {
    for (let index = 0; index < 6; index++) {
      tableContent[keys[index]] = contentList[i * 6 + index]
    }
    tableList.value.push(Object.assign({}, tableContent))
  }
  tableHeader.value = tableContent

}

// 比例列表
const ratioLists = ref([]) // 自定义的比例列表


const contractAddForm = ref();

// 添加合同
const addContract = () => {
  if (active.value > 0) {
    contractAddForm.value.validate(valid => {
      if (valid) {
        let contractEginnerList = []
        // 舍弃头和尾
        for (let i in tableList.value) {
          if (i == 0 || i == tableList.value.length - 1) {
            continue;
          } else {
            contractEginnerList.push(tableList.value[i])
          }
        }
        contractAdd.value.ifPurchase = "4"
        contractAdd.value.customerId = -1
        contractAdd.value.startTime = formatDate(contractAdd.value.date[0])
        contractAdd.value.endTime = formatDate(contractAdd.value.date[1])
        contractAdd.value.contractEginnerList = contractEginnerList
        contractAdd.value.constructionTypeList = constructionTypeList;
        selectedType.value.forEach(element => {
          contractAdd.value.selectedType.push(
            {
              id: element.id,
              number: element.number,
              unitPrice: element.unitPrice
            })
        });
        console.log(contractAdd.value)
        delete contractAdd.value.date
        post('/contract/addContract', contractAdd.value).then(result => {
          tip.success(result.message);
        });
      }
    });
  }
  active.value += 1

}

// 日期格式化函数
function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 关闭
const close = () => {
  contractAdd.contractName = '';
  contractAdd.contractDesc = '';
  contractAdd.contractState = '';
  contractAdd.workRegion = '';
  contractAdd.productNum = '';
  contractAdd.customerId = '';
  contractAdd.otherCustomer = '';
  visible.value = false;
  showRatio.value = false;
  contractAdd.productId = "";
  imageList.value = [];
  selectedType.value = [];
}

const selectedType = ref([]);
const changeType = () => {
  selectedType.value.length = 0;
  selectedType.value = []
  constructionTypeList.value.forEach(i => {
    selectedType.value.push(typeList.value.find(t => t.id === i))
  });

}



</script>

<style scoped>
.avatar-uploader-icon {
  margin: auto;
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 95px;
  text-align: center;
}
</style>